<html>
<body>
<h1>hello word!!!</h1>
<p>this is a html page</p>
<button id="playButton">Play Video</button>
<video id="videoPlayer" width="640" height="360" controls>
    Your browser does not support the video tag.
</video>
<script>
    const videoPlayer = document.getElementById('videoPlayer');
    const playButton = document.getElementById('playButton');
    const videoId = 'video1';
    let start = 0;
    let end = 0;
    let contentLength = 0;

    function fetchVideoChunk(start, end) {
        fetch(`/api/v1/stream_video?videoId=${videoId}`, {
            headers: {
                'Range': `bytes=${start}-${end}`
            }
        })
        .then(response => {
            if (response.status === 206) {
                // 将 response 作为参数传递给 loadedmetadata 事件处理程序
                videoPlayer.addEventListener('loadedmetadata', () => handleLoadedMetadata(response));
                return response.blob();
            } else {
                throw new Error('Failed to fetch video chunk');
            }
        })
        .then(blob => {
            const videoUrl = URL.createObjectURL(blob);
            videoPlayer.src = videoUrl;
        })
        .catch(error => {
            console.error('Error fetching video chunk:', error);
        });
    }

    function handleLoadedMetadata(response) {
        if (contentLength === 0) {
            contentLength = response.headers.get('Content-Length');
        } else {
            const buffer = videoPlayer.buffered;
            if (buffer.length > 0) {
                start = buffer.end(buffer.length - 1);
                end = Math.min(start + 1024 * 1024, contentLength - 1); // 请求1MB的块
                if (start < contentLength) {
                    fetchVideoChunk(start, end);
                }
            }
        }
    }

    playButton.addEventListener('click', () => {
        // 重置 start 和 end 以确保从头开始播放
        start = 0;
        end = 0;
        contentLength = 0;
        fetchVideoChunk(0, 1024 * 1024 - 1); // 初始请求1MB的块
        videoPlayer.play().catch(error => {
            console.error('Play failed:', error);
        });
    });
</script>
</body>
</html>